<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

class ImgController extends Controller
{

    /**
     * 文件上传
     * $upload obj 上传文件数据
     * $prefix string 前缀
     */
    function uploadImg(Request $request) {
        //参数验证
        $messages = [
            'required'      => ':attribute 项是必要的。',
            'file'          => ':attribute 上传数据必须是文件',
        ];

        $this->validate($request, [
            'upload'        => 'required|file',
            'prefix'        => 'required',
        ], $messages);
        // print_r($request);die;

        $file = $request->file('upload');
        // print_r($file);die;

        $image = Config::get('image');


        if (!$file->isValid()) {
            return ['status' => 1, 'msg' => '无效的文件'];
        }

        // 大小超过4M
        if ($file->getClientSize() > 4*1024*1024) {
            return ['status' => 1, 'msg' => '图片大小超过4M'];
        }

        // 设置目录
        $dirName = $image['file_store_path'] . date('Ym');
        if (!file_exists($dirName)) {
            mkdir($dirName);
        }

        $fileName = $request->prefix . time() . '.' . $file->getClientOriginalExtension();

        // 文件从临时目录移动到固定目录失败
        if(!$file->move($dirName, $fileName)) {
            return ['status' => 1, 'msg' => '文件移动失败'];
        };

        return ['status' => 0, 'file' => $image['img_url'] . date('Ym') . '/' . $fileName];
        
    }
}
